<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>可编辑内容的表格</title>
    <meta http-equiv="X-UA-Compatible" content="chrome=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="renderer" content="webkit">
    <meta name="author" content="yb">
    <meta name="keywords" content="关键词" />
    <meta name="description" content="描述" />
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
    <meta http-equiv="Expires" content="0">
    <!-- <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="../../style/css/base.css">
    <style>
        td{
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <table align="center">
        <tr>
            <td>学号</td>
            <td>姓名</td>
        </tr>
        <tr>
            <td>001</td>
            <td>dog</td>
        </tr>
        <tr>
            <td>002</td>
            <td>cat</td>
        </tr>
        <tr>
            <td>003</td>
            <td>pig</td>
        </tr>
    </table>
</body>
<script>
    $(function () {
        $("td").click(function (event) {
            //td中已经有了input,则不需要响应点击事件
            if ($(this).children("input").length > 0) {
                return false;
            }
            var tdObj = $(this);
            var preText = tdObj.html();
            //得到当前文本内容
            var inputObj = $("<input type='text' />");
            //创建一个文本框元素
            tdObj.html(""); //清空td中的所有元素
            inputObj
                .width(tdObj.width())
                //设置文本框宽度与td相同
                .height(tdObj.height())
                .css({
                    border: "0px",
                    fontSize: "17px",
                    font: "宋体"
                })
                .val(preText)
                .appendTo(tdObj)
                //把创建的文本框插入到tdObj子节点的最后
                .trigger("focus")
                //用trigger方法触发事件
                .trigger("select");
            inputObj.keyup(function (event) {
                if (13 == event.which)
                //用户按下回车
                {
                    var text = $(this).val();
                    tdObj.html(text);
                } else if (27 == event.which)
                //ESC键
                {
                    tdObj.html(preText);
                }
            });
            //已进入编辑状态后，不再处理click事件
            inputObj.click(function () {
                return false;
            });
        });
    });
</script>